import {Injectable} from '@angular/core';
import {HttpHeaders, HttpClient} from '@angular/common/http';

import {apiUrl} from '../config/config';
import {Observable} from 'rxjs/index';

@Injectable()
export class HttpService {


  private apiBaseUrl: string = apiUrl;
  private token: string = null;
  private userCode: string = null;

  private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});


  constructor(private http: HttpClient) {

  }

  /**
   * 统一发送请求
   * @param params
   * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
   */

  /*public request(params:{}): any {
  }*/

  /**
   * get请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public get(url: string, params): any {
    return this.http.get(url, {params: params})
      .toPromise()
      .then(res => this.handleSuccess(res))
      .catch(res => this.handleError(res));
  }

  public g(url: string, params): Observable<Object>{
    return this.http.get(this.apiBaseUrl +url, {params: params});
  }
  /**
   * post请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public post(url: string, params: any, callback?,errorback?): any {
    let data = this.paramFormat(params);
    console.log(data);
    if (data == '') {
      data = 'token=' + this.token + '&userCode=' + this.userCode;
    }else{
      data += '&token=' + this.token + '&userCode=' + this.userCode;
    }
    return this.http.post(this.apiBaseUrl + url, data, {headers: this.headers})
      .toPromise()
      .then(res => callback ? callback(res) : this.handleSuccess(res))
      .catch(res =>this.handleError(res,errorback));
  }

  public p(url: string, params: any):  Observable<Object> {
    let data = this.paramFormat(params);
    if (data == '') {
      data = 'token=' + this.token + '&userCode=' + this.userCode;
    }else{
      data += '&token=' + this.token + '&userCode=' + this.userCode;
    }
    return this.http.post(this.apiBaseUrl + url, data, {headers: this.headers});
  }

  /**
   * 处理请求成功
   * @param res
   * @returns {{data: (string|null|((node:any)=>any)
   */
  private handleSuccess(res) {
    return res;
  }

  /**
   * 处理请求错误
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  private handleError(error,errorback?) {
    console.log(error);
    let msg = '请求失败';
    let errorCode = 9999;
    if (error.status == 0) {
      msg = '服务器网络链接异常';
    }
    if (error.status == 400) {
      msg = '400 请求参数是否正确';
    }
    if (error.status == 404) {
      msg = '404 请检查路径是否正确';
    }
    if (error.status == 500) {
      msg = '500 请求的服务器异常';
    }

    if(errorback){
      errorback({success: false, msg: msg, code: errorCode});
    }
    return ;
  }

  // 序列化参数
  private paramFormat(data: any): string {
    let paramStr = '', name, value, subName, innerObj;
    for (name in data) {
      value = data[name];
      if (value instanceof Array) {
        for (let i of value) {
          subName = name;
          innerObj = {};
          innerObj[subName] = i;
          paramStr += this.paramFormat(innerObj) + '&';
        }
      } else if (value instanceof Object) {
        Object.keys(value).forEach((key) => {

          subName = name + '[' + key + ']';
          innerObj = {};
          innerObj[subName] = value[key];
          paramStr += this.paramFormat(innerObj) + '&';
        });
      } else if (value !== undefined && value !== null) {
        paramStr += name + '=' + value + '&';
      }
    }
    return paramStr.length ? paramStr.substr(0, paramStr.length - 1) : paramStr;
  }

}
